package hflyeer.controller;

import hflyeer.base.BaseController;
import hflyeer.base.ResultInfo;
import hflyeer.pojo.dto.UserDto;
import hflyeer.pojo.entity.User;
import hflyeer.service.UserService;
import hflyeer.utils.AssertUtil;
import hflyeer.utils.LoginUserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * UserController
 *
 * @author hflyeer
 * @date 2021-06-03
 * @describe
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {


    @Resource
    private UserService userService;

    /**
     * 登陆
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    protected ResultInfo userLogin(final String userName, final String password, HttpServletRequest request){

        UserDto loginUser = userService.login(userName,password);
        request.getSession().setAttribute("USER",loginUser);

        return this.success("登入成功", loginUser);
    }

    /**
     * 重定向到登陆页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    protected String userLogout(HttpServletRequest request){

        request.getSession().removeAttribute("USER");

        return "redirect:/index";
    }

    @RequestMapping(value = "/update_password",method = RequestMethod.POST)
    @ResponseBody
    protected ResultInfo userUpdatePassword(HttpServletRequest request,final String oldPwd, final String newPwd, final String renewPwd){

        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);

        boolean isUpdate = userService.updatePwdById(userId,oldPwd,newPwd,renewPwd);
        AssertUtil.isTrue(!isUpdate,"密码修改失败");

        return this.success("修改密码成功");
    }


    @RequestMapping(value = "/queryAllSales")
    @ResponseBody
    protected ResultInfo queryAllSales(){

       List<User> userList = userService.queryAllSales();

        return this.success("success",userList);
    }




    /*---------页面跳转--------*/

    /*跳转到修改密码界面*/
    @RequestMapping("/toPasswordPage")
    protected String toPasswordPage(){
        return "password";
    }

    /*跳转到个人信息界面*/
    @RequestMapping("/toSettingPage")
    protected String toSettingPage(){
        return "setting";
    }
}
